<template>
  <div class="blog-list-container">
    <div class="header-actions">
      <h2>博客列表</h2>
      <el-button type="primary" @click="router.push('/blogs/create')">
        <Plus /> 新增博客
      </el-button>
    </div>
    
    <el-table v-loading="loading" :data="blogs" stripe>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <!-- 将分类列从直接绑定prop改为使用作用域插槽 -->
      <el-table-column label="分类">
        <template #default="scope">
          {{ scope.row.category ? scope.row.category.name : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="text" @click="router.push(`/blogs/edit/${scope.row.id}`)">
            <Edit /> 编辑
          </el-button>
          <el-button type="text" danger @click="handleDelete(scope.row.id)">
            <Delete /> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        @size-change="fetchBlogs"
        @current-change="fetchBlogs"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { blogApi } from '@/api/blogApi'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'

const router = useRouter()
const blogs = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取博客列表
const fetchBlogs = async () => {
  loading.value = true
  try {
    const response = await blogApi.getBlogs({
      page: currentPage.value,
      size: pageSize.value
    })
    blogs.value = response.data.content
    total.value = response.data.totalElements
  } catch (error) {
    console.error('获取博客列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除博客
const handleDelete = async (id) => {
  try {
    await blogApi.deleteBlog(id)
    // 删除成功后重新获取列表
    fetchBlogs()
  } catch (error) {
    console.error('删除博客失败:', error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchBlogs()
})
</script>

<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>